<template>
	<div class="container">
		<div class="row">
			<div class="col-md-9">
				<div class="title-bar">
					<div class="title">个人资料</div>
				</div>
				<div class="col-md-6">
					<div class="panel panel-default profile">
						<div class="panel-heading">
							<div class="form-group input-group-lg">
								<img :src="state.user.profile" class="avatar"  @click="handleUpload">
								<button class="btn btn-danger btn-xs" @click="handleUpload">更改头像</button>
								<input type="file" accept=".png, .jpg, .jpeg" id="file" @change="changeAvatar"
									ref="file">
							</div>
						</div>
						<div class="panel-body">
							<div class="form-group input-group-lg">
								<div class="input-group">
									<span class="input-group-addon" id="sizing-addon1">昵称</span>
									<input type="text" v-model="state.user.username" class="form-control"
										placeholder="昵称">
								</div>
							</div>
							<div class="form-group input-group-lg">
								<div class="input-group">
									<span class="input-group-addon" id="sizing-addon1">签名</span>
									<textarea v-model="state.user.note" class="form-control" placeholder="简介" />
								</div>
							</div>

							<button class="btn btn-success btn-lg" style="width: 100%;" @click="submit">保存</button>
						</div>
					</div>

				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRefs,
		onBeforeMount
	} from 'vue';
	import {
		useRoute,
		useRouter
	} from 'vue-router'

	import {
		GetCurrentUser,
		UpdateUser
	} from '../../api/user.js'


	import {
		uploadImg
	}
	from '../../utils/upload.js'

	import {
		useUserStore
	} from '../../store/user.js'

	const route = useRoute()
	const router = useRouter()

	const userStore = useUserStore()
	const {
		userInfo
	} = toRefs(userStore)

	const file = ref(null)

	const state = reactive({
		user: ref({}),
		userId: ref('')
	})


	onBeforeMount(() => {
		initUser()
	})
	const initUser = () => {
		if (route.query && route.query.id) {
			state.userId = route.query.id;
			GetCurrentUser({
					id: state.userId
				})
				.then(({
					code,
					msg,
					data
				}) => {
					if (code == 200) {
						state.user = data.user
					}
				})
				.catch(err => {
					console.log('err', err)
				})
		}
	}
	const handleUpload = () => {
		if (file.value) {
			file.value.click()
		}
	}
	const changeAvatar = (e) => {
		const image = e.target.files[0]
		uploadImg('/api/v1/common/uploadImg', image).then(({data}) => {
			if(data.code==200){
				state.user.profile = data.data
			}
		})
	}
	const submit = () => {
		let {id,username,note,profile} = state.user
		UpdateUser({
			id,
			username,
			note,
			profile
		})
		.then(({code,msg})=>{
			if(code==200){
				initUser()
			}
		})
	}
</script>

<style>
	#file {
		display: none;
	}
</style>
